package acs.offer.server;

import java.util.HashMap;
import java.util.Map;

import acs.offer.client.ClientTask;
import acs.offer.collection.Params;
import acs.offer.constant.Constant;
import acs.offer.constant.EventType;
import acs.offer.controller.MessageObserver;
import acs.offer.pojo.RequestEnum;
import acs.offer.server.service.DmsService;
import acs.offer.util.DMSSoftTimer;
/**
 * 用于分发请求，相当于前端控制器
 * @author Administrator
 *
 */
public class DmsController implements MessageObserver {
    private static DmsController instance=new DmsController();
    private DmsController(){}
	private static final int STATE_INIT = 1;
	private static final int STATE_WAITING_OFFER = 2;// 加载数据中
	private static final int STATE_DATA_LOADED = 4;
	private int currentState = STATE_INIT;// 状态
	private Map<String,DmsService> serviceMap=new HashMap<>();
    public static DmsController getInstance(){
        return instance;
    }

    @Override
    public void handle(int eventType, Params param) {
        switch (eventType) {
            case EventType.CLICK_REQUEST:
            	this.getOrGeneratorDmsService(param).handleRequest(param);
                break;
            case EventType.RESPONSE_FOR_DATA:
            	this.getPreDmsService(param).sendResponse(param);
                break;
            case EventType.TIMEOUT_FOR_CACHE_OFFER:
            	this.getPreDmsService(param).clearCache(param);
            	break;
            case EventType.TIMEOUT_FOR_DMS_SERVICE:
            	serviceMap.remove(param.get(Constant.REQUEST_ENUM).toString());
            	break;
            case EventType.TIMEOUT_WHEN_GET_TARGET_OFFER:
            	this.getPreDmsService(param).doNotResponseDataToClient(param);
            	break;
        }
    }

	/**
	 * 得到之前生成的DmsService
	 * @param params
	 * @return
	 */
	private DmsService getPreDmsService(Params params) {
		RequestEnum requestEnum = params.get(Constant.REQUEST_ENUM);
		if(requestEnum == null) {
			System.out.println("");
		}
		DmsService dmsService = serviceMap.get(requestEnum.toString());
		if(dmsService == null) {
			throw new RuntimeException("程序出错，没有获取到前面保存的DmsService");
		}
		return dmsService;
	}
	/**
	 * 获取或创建DmsService，在刚开始处理请求时，调用此方法
	 * @param params
	 * @return
	 */
	private DmsService getOrGeneratorDmsService(Params params) {
		RequestEnum requestEnum = params.get(Constant.REQUEST_ENUM);
		DmsService dmsService = serviceMap.get(requestEnum.toString());
		if(dmsService == null) {
			dmsService=new DmsService();
			serviceMap.put(requestEnum.toString(), dmsService);
			DMSSoftTimer.getInstance().startTimer(50 * 1000, EventType.TIMEOUT_FOR_DMS_SERVICE,params);
		}
		return dmsService;
	}

	@Override
	public void removeService(String requestType) {
		// TODO Auto-generated method stub
		
	}
   
}
